package cn.edu.scau.cmi.hexiaoqing.client;

import cn.edu.scau.cmi.hexiaoqing.interProgramming.Singleton;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class SingletonClient extends Application {

	Singleton instance;

	@Override
	public void start(Stage primaryStage) {
		Text t = new Text();
		t.setFont(new Font(20));
		BorderPane bp = new BorderPane();
		Button b1 = new Button("New a president");
		b1.setOnAction(e -> {
			stage2();
		});
		Button b2 = new Button("Get the president's name");
		b2.setOnAction(e -> {
			if (instance == null) {
				t.setText("Please new a president!");
			} else {
				t.setText(instance.getName());
			}
		});
		VBox vb = new VBox(20);
		vb.getChildren().add(b1);
		vb.getChildren().add(b2);
		bp.setPadding(new Insets(50, 10, 50, 50));
		bp.setCenter(t);
		bp.setRight(vb);
		Scene s = new Scene(bp, 500, 300);
		Stage stage = new Stage();
		stage.setTitle("Singleton");
		stage.setScene(s);
		stage.show();
	}

	public void stage2() {
		Stage stage = new Stage();
		VBox vb = new VBox(20);
		vb.setAlignment(Pos.CENTER);
		TextField tf = new TextField();
		Button b = new Button("Submit");
		b.setOnAction(e -> {
			String name = tf.getText();
			if (name.equals("")) {
				Stage stage1 = new Stage();
				Text t = new Text("Please enter a name!");
				t.setFont(new Font(20));
				BorderPane bp1 = new BorderPane();
				bp1.setCenter(t);
				Scene s1 = new Scene(bp1, 300, 200);
				stage1.setTitle("ERROR");
				stage1.setScene(s1);
				stage1.show();
			} else {
				instance = Singleton.getInstance(name);
				stage.close();
			}
		});
		vb.getChildren().add(tf);
		vb.getChildren().add(b);
		BorderPane bp = new BorderPane();
		bp.setCenter(vb);
		Scene s = new Scene(bp, 300, 200);
		stage.setTitle("New President");
		stage.setScene(s);
		stage.show();
	}

	public static void main(String[] args) {
		Application.launch(args);
	}
}
